/**
 * 类似于postMessage的通信
 * @param callback 有来信时的回调
 * @param config 配置
 */
export const useChannelMessage = (
  callback: (res: { command: string; message: any }) => void,
  config?: { key?: string; autoOpen?: boolean; strict?: boolean },
) => {
  const { key = 'T3R7y9X6', autoOpen = true, strict = false } = config || {}

  const isOpen = ref(false)
  const channel = new BroadcastChannel(key)

  function EventListener({ isTrusted, data }: MessageEvent) {
    if (!strict || isTrusted) {
      try {
        const { command, message } = data
        callback({ command, message })
      } catch (e) {
        console.error('Message 解析异常')
      }
    }
  }
  function open() {
    channel.addEventListener('message', EventListener)
    isOpen.value = true
  }

  function send(command: string, message: any) {
    channel.postMessage({ command, message })
  }

  function close() {
    channel.removeEventListener('message', EventListener)
    isOpen.value = false
    // channel.close()
  }

  autoOpen && open()
  close()
  open()
  onBeforeUnmount(close)

  return {
    isOpen,
    open,
    send,
    close,
  }
}
